<template>
  <div>
  <van-nav-bar
      v-if="appnerList"
      title="确认地址"
      left-text="返回"
      right-text="确认"
      left-arrow
      @click-left="onClickLeft"
      @click-right="updateOrder"
  />

    <van-address-list
        v-if="appnerList"
        v-model="chosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
    />
    <AddressEdit v-if="addAddress"></AddressEdit>

</div>
</template>


<script>
import AddressEdit from "./AddressEdit";
import Ax from "../axios";

import { mapState } from "vuex";





export default {
  name: "addresscheck",
  components:{
    AddressEdit
  },
  computed:{
    ...mapState("login", ["token"])
  },
  data(){
    return {
      appnerList:true,
      addAddress:false,
      chosenAddressId:0,
      list:[],



    }
  },
  methods:{
    updateOrder(){
      //下订单
      const ax = new Ax(this.token)
      ax.createBasket(this.token).then(response=>{

        ax.updataOrder(response.data.id, this.token,{status: "Final", address:this.chosenAddressId}).then(response=>{
          if (response.status === 202){
            this.$router.push({name:"order"})
          }
        })
      })


    },
    onClickLeft(){
      this.$router.go(-1)

    },

    onAdd(){
      console.log("新增地址")
      this.addAddress = true
      this.appnerList = false


    },
    onEdit(item, index){
      console.log(item, index)
    },
    getUserAddress(){
      const ax = new Ax(this.token)

      let query = {
        username:sessionStorage.getItem("userinfo")
      }

      ax.getUserAddress({username:query}).then(response=>{

        //组成地址数据

        if (response.status === 200){
          response.data.data.forEach((item)=>{
            let dict = {}
            dict["id"] = item.id
            dict["name"] = item.user.username
            dict["address"] = item.province + item.area + item.city + item.detailed
            dict["isDefault"] = item.default
            dict["tel"] = 7530000

            if (item.default){
              this.chosenAddressId = item.id
            }


            this.list.push(dict)

          })

        }
      })
    }

  },
  created() {
    //获取地址
    this.getUserAddress()
    //生成ax


  }
}
</script>

<style scoped>

</style>